<?php
   namespace app\api\controller\v1;

   use app\common\lib\exception\ApiException;
   use app\common\lib\aes\IAuth;
   use app\common\lib\aes\Time;
   use think\Controller;
   use think\Cache;

   class Common extends Controller{
       /**
        * headers信息
        * @var string
        */
       public $headers = '';

       /**
        * 初始化方法
        * @author 王柯 <wangke.email@foxmail.com>
        * @return void
        */
       public function _initialize(){
           //halt($this->testAes());
           $this->checkRequestAuth();
       }

       /**
        * 检测每次app请求的数据是否合法
        * @author 王柯 <wangke.email@foxmail.com>
        * @return void
        */
       public function checkRequestAuth(){
            //获取header
           $headers = request()->header();
           //基础参数校验
           if(empty($headers['sign'])){
                throw new ApiException('sign不存在！',400);
           }
           if(!in_array($headers['apptype'],config('app.app_types'))){
               throw new ApiException('apptype不合法！',400);
           }

           if(!IAuth::checkSignPass($headers)){
               throw new ApiException('授权码sign失败！',401);
           }

           Cache::set($headers['sign'], 1, config('app.app_sign_cache_time'));

           // 1、文件  2、mysql 3、redis
           $this->headers = $headers;
       }

       /**
        * Aes加密解密测试
        * @author 王柯 <wangke.email@foxmail.com>
        * @return \app\common\lib\HexString|string
        */
       public function testAes(){
           $this->headers = request()->header();
           $data = [
               'did' => '12345dg',
               'version' => 'v1',
               'time' => Time::get13TimeStamp(),
           ];

           //$str = 'id=1&name=xiaoqian';
           //$aes_str = 'C6sATGqO8K/ZDOup0xX09RIGKurGpL8FJgQzsGwYIH4=';
           //$aes = 'bi3t+Osyo7srkP6jO/T/jtiu+ZB6f6/83Mxod7efflS+dDuX1UkRcKe33JFcK+Nn';
            //echo IAuth::setSign($data);
           return IAuth::setSign($data);
           //dump((new Aes())->encrypt($str)) ;exit;
           //echo (new Aes())->decrypt($aes_str);exit;
       }
   }